using TEngine;
using UnityEngine;
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using TMPro;

namespace GameLogic
{
	[Window(UILayer.UI)]
	public partial class Panel_Loading : UIWindow
	{
		private bool IsLoadSuccess;
		private float value;
		private float _timer;
		private bool _OpenTime;
		private TMP_Text tmp;
		private Stopwatch _LoadSw;
		protected override void OnRefresh()
		{
			_LoadSw = new Stopwatch();
			_LoadSw.Start();
			_timer = 0;
			value = 10;
			IsLoadSuccess = false;
			mloading.maxValue = 100;
			mloading.DOValue(value, 0.2f).OnComplete(() =>
			{
				GameModule.UI.ShowUI<Panel_FloatTips>();
				//检查设备是否能够访问互联网
				if (Application.internetReachability == NetworkReachability.NotReachable)
				{
					GameEvent.Send(LogicEventType.ShowTips,"The device is not connected to the network!",false);
				}
			}).OnUpdate(() =>
			{
				mLoadingTxt.text = (int)mloading.value + "%";
			});
			//更新进度条
			LoadingSystem.Instance.SetUpdateCb(UpdateProgress);
			
			LoadTxtAnim2();
		}
		protected override void RegisterEvent()
		{
		}

		private void UpdateProgress(LoadType type)
		{
			value += 15;
			mloading.DOKill(true);
			if (type == LoadType.LoadScene)
			{
				mloading.DOValue(value, 0.1f).OnStepComplete(() =>
				{
					IsLoadSuccess = true;
				}).OnUpdate(() =>
				{
					mLoadingTxt.text = (int)mloading.value + "%";
				});
			}
			else
			{
				mloading.DOValue(value, 0.1f).OnUpdate(() =>
				{
					mLoadingTxt.text = (int)mloading.value + "%";
				});
			}
		}
		protected override void OnUpdate()
		{
			//base.OnUpdate();
			
			if (IsLoadSuccess && LoadingSystem.Instance.loadType == LoadType.None)
			{
				Close();
			}
			//LoadTxtAnim();
		}
		Tween textTween;
		private void LoadTxtAnim2()
		{
			string tempTxt = "";
			if(string.IsNullOrEmpty(tmp.text)) return;
			string baseTxt = tmp.text;
			textTween = DOTween.To(() => tempTxt, value =>
			{
				tempTxt = value;
				tmp.text = baseTxt + tempTxt;
			}, "...", 1.5f).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
			
		}
		protected override void Close()
		{
			base.Close();
			_LoadSw.Stop();
			Log.Info($"加载总时长：{_LoadSw.ElapsedMilliseconds}ms");
		}
		protected override void OnDestroy()
		{
			base.OnDestroy();
			
		}
	}
}
